<?php
namespace app\common\controller;
use think\facade\Db;

/**
 * Class AdminController
 * @package app\common\controller
 */
class Preferential{
	//公用
	private $base_time = 0;

	private $redPaper = 0;//红包
	//卡券组合
	private $cardVoucherList = [];
	
	
	private $member_id = 0;
	private $store_id = 0;
	
	private $server_id = 0;
	private $type = 0;
	private $amount = 0;
	//满减
	private $fullMinusMoney = 0;//满减
	private $fullMinusType = 1;
	private $min_amount = 0;
	private $max_amount = 0;
	private $fullMinusId = 0;
	private $start_period = 0;
	private $end_period = 0;


	public function __construct($member_id,$store_id,$server_id=0,$type=0,$amount=0){
		$this->member_id = $member_id;
		$this->store_id = $store_id;
		$this->base_time = time();
		$this->server_id = $server_id;
		$this->type = $type;
		$this->amount = $amount;

	}

	public function getRedPaper(){
		return $this->redPaper;
	}

	public function getFullMinusMoney(){
		return $this->fullMinusMoney;
	}
	public function getFullMinusId(){
		return $this->fullMinusId;
	}


	public function cardVoucher(){
		
		$couponList = $this->coupon();
		$cardList = $this->card();
		return $this->cardVoucherList = array_merge($couponList,$cardList);
	}

	private function coupon(){
		//$store_id,$mem_id,$server_type,$server_id,$min_amount
		$pt_data = [];
		$interflow = interflow($this->store_id);
		
	    $storeMemberCoupon = Db::name('store_member_coupon') -> where(['members_id' => $this->member_id,'status' => 0])->whereIn('store_id',$interflow) -> where('out_time','>=',$this->base_time) -> where('get_time','<=',$this->base_time) -> field('c_id,cm_id as member_coupon_id,store_id') -> select() -> toArray();
	    

	    //优惠券信息
	    $couponInfo =[];
	    foreach ($storeMemberCoupon as $key => $value) {
	        $cou = Db::name('store_coupon') -> where('id',$value['c_id']) -> field('id as coupon_id,store_coupon_name as coupon_name,store_coupon_type_type as coupon_type,is_interflow,price,full_price') -> findOrEmpty();
	        if(count($cou) > 0){
	        	if($cou['is_interflow'] == 1){
					$cou['member_coupon_id'] = $value['member_coupon_id'];
					$cou['checked'] = false;

			        array_push($couponInfo,$cou);
				}else{
		            if($value['store_id'] == $this->store_id){
		                $cou['member_coupon_id'] = $value['member_coupon_id'];
						$cou['checked'] = false;
						array_push($couponInfo,$cou);   
					}
			    }
	        }
			
		} 
	    //根据该服务可用优惠券    
	    foreach ($couponInfo as $key => $value) {
	        $info = Db::name('store_coupon_server') -> where(['server_id' => $this->server_id,'server_type' => $this->type]) -> where('store_coupon_id',$value['coupon_id']) -> findOrEmpty();
	        $couponInfo[$key]['type'] = 'coupon';
	        if($info){
	            $couponInfo[$key]['ishow'] = 1; 
	        }else{
	            $couponInfo[$key]['ishow'] = 0; 
	        }
	    }
	 
	    $store_data = [];
	    //1.满减券2-抵用券3-免费券4.普通券5.折扣券
	    foreach ($couponInfo as $key => $value) {
	        if($value['ishow'] == 1){
	            if($value['coupon_type'] == 1 || $value['coupon_type'] == 2 || $value['coupon_type'] == 4){
	            	if($value['coupon_type'] == 1 || $value['coupon_type'] == 2){
	            		$value['server_price'] = $this->amount - $value['price'];
	            	}else{
	            		$value['server_price'] = $value['price'];
	            	}
	    			if($this->amount >= $value['full_price']){
	                	array_push($store_data, $value);
			    	}
			    }else{
			    	if($value['coupon_type'] == 3){
			    		$value['server_price'] = 0;
			    	}
			    	if($value['coupon_type'] == 5){
			    		$value['server_price'] = $this->amount * ($value['price'] * 10)/100;
			    	}
			        array_push($store_data, $value);
				}

	        }
	    }
	    $data = array_merge($pt_data,$store_data);
	    return $data;
	}

	private function card(){
		//$server_id,$type,$member_id,$store_id
	    $car_number = "";
	    $myCar = Db::name('members_car')->where('member_id', $this->member_id)->where('default', 1)->where('delete', 0)->find();
	    $memberMobile = Db::name('members') -> where('members_id',$this->member_id) -> value('members_mobile');
	    if($myCar){
	        $car_number = $myCar['car_card'];
	    }else{
	        
	        $customer = Db::name('customers') -> where(['tel' => $memberMobile,'store_id' => $this->store_id]) -> field('id,car_number') -> find();
	        if($customer){
	            $car_number = $customer['car_number'];
	        }
	        
	    }
        
	    $recordId = Db::name('membership_records') -> where('store_id',$this->store_id) -> where('mobile',$memberMobile) -> column('id');

	    //用户已购买电子卡
	    $cardAll = Db::name('package_card') -> where(['is_pay' => 1]) -> whereIn('record_id',$recordId) -> where('out_date_time','>=',$this->base_time) -> select() -> toArray();
	    
	    $cards = [];
	    foreach ($cardAll as $key => $value) {
	        if($value['car_number']){
	            if($car_number != $value['car_number']){
	                unset($cardAll[$key]);
	            }
	        }   
	        
	    }

	    foreach ($cardAll as $key => $value){
	        array_push($cards,$value);
	    }  
	    $this->couponList = $cards;
	    $data = [];
	    if(count($cards) > 0){
	        //购买服务次数统计
	        foreach ($cards as $key => $value) {
	            //服务次数
	            $buyNum = Db::name('card_content') -> where(['cate_id' => $this->server_id,'type' => $this->type,'card_id' => $value['card_id']]) -> value('frequency');
	            //已用服务次数统计
	            $orderIds = Db::name('orders_server') -> where(['ecards_id' => $value['id'],'server_id' => $this->server_id,'type' => $this->type]) -> column('orders_id');
	            $usedOrderIds = Db::name('orders') -> whereIn('orders_id',$orderIds) -> whereIn('orders_status',[1,2]) -> column('orders_id');
	            $count = Db::name('orders_server') -> whereIn('orders_id',$usedOrderIds) -> sum('card_server_num');
	            $leftNum = $buyNum - $count;
	            if($leftNum > 0){
	                $card = Db::name('card') -> where(['id' => $value['card_id']]) -> find();
	                $tmp['cardName'] = $card['card_name'];
	                $tmp['enabledNum'] = $leftNum;
	                $tmp['ecards_id'] = $value['id'];
	                $tmp['totalNum'] = $buyNum;
	                $tmp['card_server_id'] = Db::name('card_server') -> where(['server_id' => $server_id,'server_type' => $type,'card_id' => $value['card_id']]) -> value('id');
	                $tmp['card_id'] = $value['card_id'];
	                $tmp['type'] = "card";
	                array_push($data, $tmp);
	            }

	        }

	    }
	    return $data;
	}

	public function fullAmountMinus(){
		$storeReduction = Db::name('store_reduction') -> where(['store_id' => $this->store_id,'status' => 1,'is_get' => 0,'state' => 1]) -> whereTime('start_time','<=',$this->base_time) -> whereTime('end_time', '>=',$this->base_time) -> where('max_amount','>=',$this->amount) -> where('min_amount','<=',$this->amount) -> field('id,type,price,min_amount,max_amount,start_period,end_period') -> findOrEmpty();
		if(count($storeReduction) > 0){
			$this->fullMinusType = $storeReduction['type'];
			$this->min_amount = $storeReduction['min_amount'];
			$this->max_amount = $storeReduction['max_amount'];
			$this->fullMinusId = $storeReduction['id'];
			$this->fullMinusMoney = $storeReduction['price'];
			$this->start_period = $storeReduction['start_period'];
			$this->end_period = $storeReduction['end_period'];
			$this->fullMinusMoney();
		}
		return $this;
	}

	/**
	 * [fullReductionAndFullGiftResult description]
	 * @Author   ZYL
	 * @DateTime 2021-07-28T09:15:25+0800
	 * @Param    Description
	 * @param    array                    $arr  [满减满赠符合要求的ID集合]
	 * @param    integer                  $type [1:现金 2-优惠券]
	 * @return   [type]                         [description]
	 */
	private function fullMinusMoney(){
		switch ($this->fullMinusType) {
			case '1'://累计消费满减(本单计算在内)
				$data = cumulativeStatistics($this->member_id,$this->store_id);                        
	            if(($data[1] + $this->amount) < $this->min_amount || ($data[1] + $this->amount) > $this->max_amount){
	                $this->fullMinusId = 0;
					$this->fullMinusMoney = 0;
	            }
				break;
			case '2'://单次消费满减      
                if($this->amount < $this->min_amount || $this->amount > $this->max_amount){
	                $this->fullMinusId = 0;
					$this->fullMinusMoney = 0;
            	} 
                  
               
				break;
			case '3'://时间段满减金额
				$data = cumulativeStatistics($this->member_id,$this->store_id,$this->start_period,$this->end_period);
				$tempFullMinusMoney = $data[1];
				if($this->base_time >= $this->start_period && $this->base_time <= $this->end_period){
					$tempFullMinusMoney = $data[1] + $this->amount;
				}
                if($tempFullMinusMoney < $this->min_amount || $tempFullMinusMoney > $this->max_amount){
	                $this->fullMinusId = 0;
					$this->fullMinusMoney = 0;
	            }
				break;
			case '4'://累计消费次数
				$data = cumulativeStatistics($this->member_id,$this->store_id);
                if(($data[0] + 1) < $this->min_amount || ($data[0] + 1) > $this->max_amount){
	                $this->fullMinusId = 0;
					$this->fullMinusMoney = 0;
	            }
                
                        
                
				break;
			case '5'://时间段累计消费次数
				$data = cumulativeStatistics($this->member_id,$this->store_id,$this->start_period,$this->end_period);
                $tempFullMinusCount = $data[0];
				if($this->base_time >= $this->start_period && $this->base_time <= $this->end_period){
					$tempFullMinusCount = $data[0] + $this->amount;
				}
                if($tempFullMinusCount < $this->min_amount || $tempFullMinusCount > $this->max_amount){
	                $this->fullMinusId = 0;
					$this->fullMinusMoney = 0;
	            }
				break;	
		}
	}

	//红包
	public function hongbao(){
	    $redPacket = Db::name('store_redenvelope_record') -> whereIn('store_id',$this->store_id) -> where(['members_id'=>$this->member_id]) -> sum('price'); 

	    if($this->amount >= $redPacket){
	    	$hongbao = $redPacket;
	    }else{
	    	$hongbao = $this->amount;
	    }
	    $this->redPaper = $hongbao > 0 ? $hongbao : 0;
	    return $this;   
	}

}